﻿using System.Security.Cryptography;
using System.Text;

namespace ZFB.Common
{
    public class CommonHelper
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CalcMD5(string str)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
            return CalcMD5(bytes);
        }

        public static string CalcMD5(byte[] bytes)
        {
            using MD5 md5 = MD5.Create();

            byte[] computeBytes = md5.ComputeHash(bytes);
            string result = "";
            for (int i = 0; i < computeBytes.Length; i++)
            {
                result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
            }
            return result;

        }

        public static string CalcMD5(Stream stream)
        {
            using MD5 md5 = MD5.Create();
            byte[] computeBytes = md5.ComputeHash(stream);
            string result = "";
            for (int i = 0; i < computeBytes.Length; i++)
            {
                result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
            }
            return result;
        }
        /// <summary>
        /// 加盐和验证码
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string CreateVerifyCode(int len)
        {
            char[] data = { 'a','c','d','e','f','h','k','m',
                'n','r','s','t','w','x','y'};
            StringBuilder sb = new();
            Random rand = new();
            for (int i = 0; i < len; i++)
            {
                int index = rand.Next(data.Length);//[0,data.length)
                char ch = data[index];
                sb.Append(ch);
            }
            return sb.ToString();
        }  
        


        /// <summary>
        /// 生成随机数字 长度为5 
        /// </summary>
        public static string CreateRandomCode() 
        {
            return Str(false);
        }
        /// <summary>
        /// 生成随机数字
        /// </summary>
        /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
        public static string Str(bool Sleep)
        {
            if (Sleep) System.Threading.Thread.Sleep(3);
            char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            string result = "";
            int n = Pattern.Length;
            System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < 5; i++)
            {
                int rnd = random.Next(0, n);
                result += Pattern[rnd];
            }
            return result;
        }


    }
}